<template>
  <div class="home-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>游戏房间</h1>
    </div>

    <!-- 房间列表（竖向可滑动） -->
    <div class="rooms-vertical-container">
      <div class="rooms-list-vertical">
        <div
          class="room-item"
          v-for="(room, index) in rooms"
          :key="index"
          :style="{ borderColor: room.color }"
        >

          <!-- 房间信息 -->
          <div class="room-info">
            <div class="room-name">{{ room.name }}</div>
            <div class="room-meta">
              在线: {{ room.online }}
            </div>
          </div>

          <!-- 进入按钮 -->
          <button class="join-btn" @click="enterRoom(room.id)">
            进入
          </button>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <button class="bar-btn" @click="handleCreate">
        <span>创建房间</span>
      </button>
      <button class="bar-btn" @click="goToProfile">
        <span>个人资料</span>
      </button>
      <button class="bar-btn logout" @click="handleLogout">
        <span>退出登录</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import {useRouter} from "vue-router"
import {ref, onMounted, onUnmounted, watchEffect} from "vue"
import {onEvent, offEvent, initEventBus, connectionStatus} from "@/utils/eventBus"
import axios from "axios";
import config from "@/config"

const router = useRouter();
let rooms = ref([]);

const eventFunction = (data) => {
  getRooms();
}

onMounted(() => {
  // 确保连接已初始化
  initEventBus()
  onEvent('update-room', eventFunction)
})

onUnmounted(() => {
  offEvent('update-room', eventFunction)
  if (connectionStatusWatch) {
    connectionStatusWatch()
  }
})

// 监听连接状态变化
let connectionStatusWatch
onMounted(() => {
  // 确保连接已初始化
  initEventBus()
  onEvent('update-room', eventFunction)

  // 监听连接状态
  connectionStatusWatch = watchEffect(() => {
    console.log('SSE 连接状态:', connectionStatus.value)
    if (connectionStatus.value === 'disconnected') {
      console.log('SSE 连接已断开，尝试重新连接...')
      initEventBus()
    } else if (connectionStatus.value === 'connected') {
      console.log('SSE 连接已恢复')
      // 重新订阅事件，确保不会错过任何更新
      offEvent('update-room', eventFunction)
      onEvent('update-room', eventFunction)
    }
  })
})




// 延迟执行，确保事件系统已就绪
setTimeout(() => {
  verify()
  getRooms()
  checkInRoom()
}, 500)





const enterRoom = async (roomId) => {
    let response = await axios.post(config.api + 'data/join-room', {
        id: roomId
    }, {
        withCredentials:true
    })
    if (response.data.status != "0") {
      alert(response.data.msg)
    }
    else {
      router.replace("/game")
    }
}




//一进到该界面先验证一下登录情况，验证不通过提示请登录然后返回登录界面
async function verify() {
    let response = await axios.post(config.api + 'auth/verify', { }, {
        withCredentials: true
    });
    if (response.data.status == "-1") {
        alert("您还没有登录");
        router.push("/login");  
    }
}
async function getRooms (){
    let response = await axios.post(config.api + 'data/get-rooms', { }, {
        withCredentials: true
    });
    rooms.value = response.data.rooms ? response.data.rooms: []
}

async function checkInRoom() {
  let response = await axios.post(config.api + "data/in-room", { }, {
    withCredentials: true
  })
  if (response.data.inroom == 1)  router.replace('/game')
}


function handleCreate() {
    router.push('/create-room');
}

function goToProfile() {
  router.replace('/profile');
}


async function handleLogout() {
  let response = await axios.post(config.api + 'auth/logout', { }, {
    withCredentials: true
  });
  if (response.data.status == '0') {
    alert(response.data.msg);
    router.replace('/login');
  }
}

</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.home-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: url("@/pic/fengmian4.png");
  background-size: cover;
  background-position: center;
  font-family: 'Arial', sans-serif;
  padding: 20px 15px 80px;
}

/* 页面标题 */
.page-title {
  width: 100%;
  text-align: center;
  margin-bottom: 20px;
}
.page-title h1 {
  font-size: 24px;
  color: #333;
  font-weight: bold;
}

/* 竖向房间容器（可滚动） */
.rooms-vertical-container {
  width: 100%;
  max-height: calc(100vh - 220px);
  overflow-y: auto;
  padding: 0 10px;
  margin-bottom: 15px;
}

.rooms-vertical-container::-webkit-scrollbar {
  width: 6px;
}
.rooms-vertical-container::-webkit-scrollbar-thumb {
  background-color: rgba(100, 100, 100, 0.3);
  border-radius: 3px;
}

/* 竖向房间列表 */
.rooms-list-vertical {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 每个房间项 */
.room-item {
  display: flex;
  align-items: center;
  background-color: white;
  border: 2px solid #ddd;
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}
.room-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.12);
}

/* 房间表情图标 */
.room-emoji {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  margin-right: 12px;
}

/* 房间信息区 */
.room-info {
  flex: 1;
}
.room-info .room-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}
.room-meta {
  font-size: 13px;
  color: #666;
}

/* 进入按钮 */
.join-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  font-size: 14px;
  font-weight: bold;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.join-btn:hover {
  background-color: #0056b3;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  background-color: rgba(255, 255, 255, 0.98);
  padding: 12px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border-top: 1px solid #eee;
}

.bar-btn {
  flex: 1;
  padding: 12px 10px;
  font-size: 14px;
  color: #007bff;
  font-weight: bold;
  text-align: center;
  border: none;
  background: none;
  outline: none;
  cursor: pointer;
  transition: color 0.2s;
}

.bar-btn:hover {
  color: #0056b3;
}

.bar-btn.logout {
  color: #dc3545;
}

.bar-btn.logout:hover {
  color: #c82333;
}

/* 小屏适配 */
@media (max-width: 480px) {
  .page-title h1 {
    font-size: 22px;
  }

  .room-item {
    padding: 10px;
  }

  .room-emoji {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }

  .room-info .room-name {
    font-size: 15px;
  }

  .room-meta {
    font-size: 12px;
  }

  .join-btn {
    padding: 7px 14px;
    font-size: 13px;
  }

  .bar-btn span {
    font-size: 14px;
  }
}
</style>